package com.mls.wms.android.widget.inwh;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.InventoryStatusCode;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.model.InventoryStatusModel;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.ViewUtils;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-14.
 */
public class InventoryStatusActivity extends BaseActivity {
    private long locationId = 0L;

    private EditText etLocationNo = null;
    private EditText etOldStatus = null;
    private RadioGroup radioGroup = null;

    private Button btnContinue = null;

    private InventoryStatusCode oldStatus = null;
    private InventoryStatusCode newStatus = InventoryStatusCode.GOOD;

    private AnimDialogFragment progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_inventory_status_adjust);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        this.etLocationNo = (EditText) this.findViewById(R.id.act_inventory_status_adjust_et_location_no);
        this.etOldStatus = (EditText) this.findViewById(R.id.act_inventory_status_adjust_et_old_status);
        this.radioGroup = (RadioGroup) this.findViewById(R.id.act_inventory_status_adjust_rg);

        this.etLocationNo.setWidth(this.etOldStatus.getWidth());

        this.btnContinue = (Button) this.findViewById(R.id.act_inventory_status_adjust_btn_continue);


        //文本框事件
        List<EditText> ets = ViewUtils.getDescendants(this, EditText.class, false);
        for (final EditText item : ets) {
            if (item.isEnabled() == true && item.getVisibility() == View.VISIBLE) {
                item.setSelectAllOnFocus(true);//获取焦点全选
                item.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                            return onEnterDownEditText(v);
                        }

                        return false;
                    }
                });
                item.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            return onEnterDownEditText(v);
                        }
                        return false;
                    }
                });
            }
        }
        //RadioGroup
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.act_inventory_status_adjust_rd_good) {
                    newStatus = InventoryStatusCode.GOOD;
                } else {
                    newStatus = InventoryStatusCode.BAD;
                }
            }
        });
        //按钮事件
        this.btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSubmit();
            }
        });

    }

    /**
     * 按下回车
     *
     * @param view
     * @return
     */
    private boolean onEnterDownEditText(View view) {
        if (view.getId() == this.etLocationNo.getId()) {
            isValidLocation();
            return true;
        }

        return false;
    }

    private void isValidLocation() {
        if (true == TextUtils.isEmpty(this.etLocationNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_location_no_not_null), etLocationNo);
        } else {
            String url = ServicePort.getUrl(ServicePort.InventoryStatusLocation).replace("{restfulid0}", this.etLocationNo.getText().toString().trim());
            get(url, null, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            InventoryStatusModel model = new InventoryStatusModel();
                            model = model.parseJson(result.getResult());
                            locationId = model.getLocationId();

                            if (InventoryStatusCode.GOOD.toString().equals(model.getInventoryStatusCode())) {
                                oldStatus = InventoryStatusCode.GOOD;
                                etOldStatus.setText(InventoryStatusCode.GOOD.toCn());
                            } else if (InventoryStatusCode.BAD.toString().equals(model.getInventoryStatusCode())) {
                                oldStatus = InventoryStatusCode.BAD;
                                etOldStatus.setText(InventoryStatusCode.BAD.toCn());
                            } else {
                                oldStatus = null;
                                etOldStatus.setText("");
                            }

                            radioGroup.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, etLocationNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, etLocationNo);
                }
            }, 1);
        }
    }


    private boolean checkSubmit() {
        if (this.locationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_location_no_not_null), this.etLocationNo);
            return false;
        } else if (oldStatus == null || newStatus == null || oldStatus.toString().equals(newStatus.toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_inventory_status_error), this.radioGroup);
            return false;
        }


        return true;
    }


    private void doSubmit() {
        if (true == this.checkSubmit()) {
            progressDialog.show(getFragmentManager(), this.toString());
            JSONObject data = null;
            try {
                data = new JSONObject();
                data.put("locationId", this.locationId);
                data.put("status", this.newStatus.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            post(ServicePort.getUrl(ServicePort.InventoryStatusLocationInsert), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            locationId = 0L;
                            etLocationNo.setText("");
                            etOldStatus.setText("");

                            etLocationNo.requestFocus();
                            progressDialog.dismiss();
                            return;
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        progressDialog.dismiss();
                        showDialog(errorMsg, radioGroup);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    progressDialog.dismiss();
                    showDialog(s, radioGroup);
                }
            }, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (this.etLocationNo != null) {
            switch (requestCode) {
                case ScanTypeConstants.SCAN_BAR_CODE:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        this.etLocationNo.setText(bundle.getString(Intents.Scan.RESULT, ""));
                        this.etLocationNo.requestFocus();
                        onEnterDownEditText(this.etLocationNo);
                    }
                default:
                    break;
            }
        }
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_text_inventory_status_edit;
    }
}

